package com.wclass.controller.app;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wclass.common.ReturnObject;
import com.wclass.entity.*;
import com.wclass.interceptor.BaseContextHandler;
import com.wclass.interceptor.IgnoreAuth;
import com.wclass.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 轮播 前端控制器
 * </p>
 *
 * @author 张浩高
 * @since 2018-12-21
 */
@Api(description = "app首页接口")
@RestController
@RequestMapping("/home")
public class BaseHomeController {

    @Autowired
    private IBaseCarouselService iBaseCarouselService;
    @Autowired
    private IBaseNoticeService iBaseNoticeService;
    @Autowired
    private ICourseChapterService iCourseChapterService;
    @Autowired
    private ICourseInfoService iCourseInfoService;
    @Autowired
    private IBaseAppUserService iBaseAppUserService;
    @Autowired
    private ICourseTypeService iCourseTypeService;
    @Autowired
    private IIndexSearchWordService iIndexSearchWordService;
    @Autowired
    private IPostsInfoService iPostsInfoService;

    @IgnoreAuth
    @ApiOperation("获取首页轮播")
    @RequestMapping(value = "/getCarouselList", method = RequestMethod.POST)
    public ReturnObject<List<BaseCarousel>> getCarouselList(@ApiParam("类型，1：学生端，2：教师端") @RequestParam(defaultValue = "1") Integer type) {
        EntityWrapper<BaseCarousel> ew = new EntityWrapper<>();
        List<BaseCarousel> list = iBaseCarouselService.selectList(ew.eq("type", type));
        return new ReturnObject<>(0, "获取成功", list);
    }

    @ApiOperation("获取通知列表（类型 1 学生 2 老师 3 系统）")
    @RequestMapping(value = "/getNoticeList", method = RequestMethod.POST)
    public ReturnObject<Page<BaseNotice>> getNoticeList(@ApiParam("每页条数") @RequestParam(defaultValue = "10") Integer limit,
                                                        @ApiParam("页数") @RequestParam(defaultValue = "1") Integer offset,
                                                        @ApiParam("类型 1 学生 2 老师 3 系统") @RequestParam(defaultValue = "1") Integer type) {

        EntityWrapper<BaseNotice> ew = new EntityWrapper<>();
        ew.eq("type", type);
        Page<BaseNotice> obj = iBaseNoticeService.selectPage(new Page<>(offset, limit), ew);
        return new ReturnObject<>(0, "获取成功", obj);
    }

    @ApiOperation("获取通知详情")
    @RequestMapping(value = "/getNoticeInfo", method = RequestMethod.POST)
    public ReturnObject<BaseNotice> getNoticeInfo(@ApiParam("通知公告id【必填】") @RequestParam Long NoticeId) {
        return new ReturnObject<>(0, "获取成功", iBaseNoticeService.selectById(NoticeId));
    }

    @IgnoreAuth
    @ApiOperation("获取正在直播列表")
    @RequestMapping(value = "/getLiveCourseList", method = RequestMethod.POST)
    public ReturnObject<List<Map<String, Object>>> getLiveCourseList() {
        List<Map<String, Object>> list = Lists.newArrayList();
        EntityWrapper<CourseChapter> ew = new EntityWrapper<>();
        ew.eq("type", 1);
        Page<CourseChapter> obj = iCourseChapterService.selectPage(new Page<>(1, 8), ew);
        for (CourseChapter info : obj.getRecords()) {
            CourseInfo courseInfo = iCourseInfoService.selectById(info.getCourseInfoId());
            if (courseInfo != null) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("courseId", courseInfo.getId());
                map.put("courseChapterId", courseInfo.getId());
                map.put("imgUrl", courseInfo.getCoverImgUrl());
//                if (BaseContextHandler.getUserID() != null) {
//                    map.put("isBuy", iCouresOrderService.selectCount(new EntityWrapper<CouresOrder>().eq(
//                            "pay_person_id", BaseContextHandler.getUserID()).eq("pay_state", 1)) == 0 ? 0 : 1);
//                }
                map.put("name", courseInfo.getName());
                map.put("fixtureNum", courseInfo.getFixtureNum());
                map.put("userHeadImg", courseInfo.getPictureAddress());
                map.put("userName", courseInfo.getNickName());
                list.add(map);
            }
        }
        return new ReturnObject<>(0, "获取成功", list);
    }

    @IgnoreAuth
    @ApiOperation("获取课程分页")
    @RequestMapping(value = "/getCoursePage", method = RequestMethod.POST)
    public ReturnObject<List<Map<String, Object>>> getCoursePage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") Integer limit,
                                                                 @ApiParam("页数") @RequestParam(defaultValue = "1") Integer offset,
                                                                 @ApiParam("1：免费，2：精品") @RequestParam Integer type,
                                                                 @ApiParam("课程类型id") Integer courseTypeId) {
        EntityWrapper<CourseInfo> ew = new EntityWrapper<>();
        ew.eq("info.audit_state", 1);
        if (type == 1)
            ew.eq("info.amount", 0);
        else
            ew.gt("info.amount", 0);
        if (courseTypeId != null) {
            List<CourseType> typeList = iCourseTypeService.selectList(new EntityWrapper<CourseType>().eq("p_id", courseTypeId));
            String typeIds = "";
            for (CourseType courseType : typeList) {
                typeIds += courseType.getId() + ",";
            }
            ew.in("info.course_type_id", typeIds.substring(0 , typeIds.length() - 1));
        }
        ew.orderBy("info.crt_time", false);
        Page<CourseInfo> obj = iCourseInfoService.selectPage(new Page<>(offset, limit), ew);

        List<Map<String, Object>> list = Lists.newArrayList();
        for (CourseInfo info : obj.getRecords()) {

            Map<String, Object> map = Maps.newHashMap();
            map.put("courseId", info.getId());
            map.put("name", info.getName());
            map.put("amount", info.getAmount());
            map.put("fixtureNum", info.getFixtureNum());
            map.put("star", info.getStar());
            map.put("coverImgUrl", info.getCoverImgUrl());
//            if (BaseContextHandler.getUserID() != null) {
//                map.put("isBuy", iCouresOrderService.selectCount(new EntityWrapper<CouresOrder>().eq("pay_person_id",
//                        BaseContextHandler.getUserID()).eq("pay_state", 1)) == 0 ? 0 : 1);
//            }
            list.add(map);
        }
        return new ReturnObject<>(0, "获取成功", list);
    }

    @IgnoreAuth
    @ApiOperation("推荐老师")
    @RequestMapping(value = "/getTeacherPage", method = RequestMethod.POST)
    public ReturnObject<List<Map<String, Object>>> getTeacherPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") Integer limit,
                                                                  @ApiParam("页数") @RequestParam(defaultValue = "1") Integer offset) {
        EntityWrapper<BaseAppUser> ew = new EntityWrapper<>();
        ew.eq("type", "0").eq("audit_status", "0");
        ew.orNew().eq("state", "0").eq("type", "1");
        ew.orderBy("crt_time", false);
        Page<BaseAppUser> obj = iBaseAppUserService.selectPage(new Page<>(offset, limit), ew);

        List<Map<String, Object>> list = Lists.newArrayList();
        for (BaseAppUser info : obj.getRecords()) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("userId", info.getId());
            map.put("name", info.getNickName());
            map.put("imgUrl", info.getPictureAddress());
            map.put("postname", info.getPostname());
            list.add(map);
        }
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), list);
    }

    @IgnoreAuth
    @ApiOperation("获取首页搜索历史和热门搜索")
    @RequestMapping(value = "/getPostsWordList", method = RequestMethod.POST)
    public ReturnObject<Object> getPostsWordList(@ApiParam("用户id") Long userId) {
        Map<String, Object> map = Maps.newHashMap();
        if (userId != null) {
            Page<IndexSearchWord> obj = iIndexSearchWordService.selectPage(new Page<>(1, 10),
                    new EntityWrapper<IndexSearchWord>().eq("user_id", userId).orderBy("crt_time", false));
            map.put("historyWords", obj.getRecords());
        } else {
            map.put("historyWords", null);
        }
        Page<IndexSearchWord> obj_hot = iIndexSearchWordService.getHotIndexSearch(new Page<>(1, 10));
        map.put("hotWords", obj_hot.getRecords());
        return new ReturnObject<>(0, "获取成功", map);
    }

    @ApiOperation("删除用户搜索历史")
    @RequestMapping(value = "/delUserSearchWord", method = RequestMethod.POST)
    public ReturnObject<Object> delUserSearchWord(@ApiParam("用户id") Long userId) {
        iIndexSearchWordService.delete(
                new EntityWrapper<IndexSearchWord>().eq("user_id", userId));

        return new ReturnObject<>(0, "删除成功");
    }

    @IgnoreAuth
    @ApiOperation("获取首页搜索列表")
    @RequestMapping(value = "/getIndexSearchList", method = RequestMethod.POST)
    public ReturnObject<Map<String, Object>> getIndexSearchList(@ApiParam("每页条数") @RequestParam(defaultValue = "10") Integer limit,
                                                                @ApiParam("页数") @RequestParam(defaultValue = "1") Integer offset,
                                                                @ApiParam("搜索类型，0：推荐，1：群，2：用户，3：课程，4：帖子") @RequestParam Integer type,
                                                                @ApiParam("搜索关键词") @RequestParam String searchName,
                                                                @ApiParam("用户id") Long userId,
                                                                @ApiParam("课程排序（综合:info.crt_time,好评：info.feedback_rate,人气:info" +
                                                                        ".fixture_num,价钱:info.amount）") @RequestParam(defaultValue =
                                                                        "info.crt_time") String courseSort,
                                                                @ApiParam("排序方式（0:正序，1:倒叙）") @RequestParam(defaultValue = "1") Integer isAsc,
                                                                @ApiParam("课程播放类型（0：直播，1：点播）") Integer liveType,
                                                                @ApiParam("课程最低价(单位：分)") Long startAmount,
                                                                @ApiParam("课程最高价(单位：分)") Long endAmount,
                                                                @ApiParam("课程类型id") Long courseTypeId,
                                                                @ApiParam("帖子排序（综合:info.crt_time,人气:info.like_num,收藏info.collect_num）") @RequestParam(defaultValue =
                                                                        "info.crt_time") String postsSort,
                                                                @ApiParam("用户类型，0:学生，1：老师") @RequestParam(defaultValue = "1") Integer userType){
        Map<String, Object> map = Maps.newHashMap();
        map.put("groupTotal", null);map.put("groupList", null);
        map.put("userTotal", null);map.put("userList", null);
        map.put("courseTotal", null);map.put("courseList", null);
        map.put("postsInfoTotal", null);map.put("postsInfoList", null);
        if (type == 0 || type == 1) {
            Page<CourseInfo> groupObj = iCourseInfoService.selectPage(new Page<>(offset, limit),
                    new EntityWrapper<CourseInfo>().like("LOWER(info.class_name)", searchName.toLowerCase()).orderBy("info.star", false));
            map.put("groupTotal", groupObj.getTotal());map.put("groupList", groupObj.getRecords());
        }
        if (type == 0 || type == 2) {
            EntityWrapper<BaseAppUser> ew = new EntityWrapper<>();
            ew.like("LOWER(nick_name)", searchName.toLowerCase());
            ew.eq("type", userType);
            ew.orderBy("fan_num", false);

            Page<BaseAppUser> userObj = iBaseAppUserService.selectPage(new Page<>(offset, limit), ew);
            map.put("userTotal", userObj.getTotal());map.put("userList", userObj.getRecords());
        }
        if (type == 0 || type == 3) {
            EntityWrapper<CourseInfo> ew = new EntityWrapper<>();
            ew.eq("info.audit_state", 1);
            ew.like("LOWER(info.name)", searchName.toLowerCase());
            if (liveType != null) {
                ew.eq("info.live_type", liveType);
            }
            if (startAmount != null) {
                ew.ge("info.amount", startAmount);
            }
            if (endAmount != null) {
                ew.le("info.amount", endAmount);
            }
            if (courseTypeId != null)
                ew.eq("info.course_type_id", courseTypeId);
            ew.orderBy(courseSort, isAsc == 1 ? false : true).orderBy("info.star", false);

            Page<CourseInfo> courseObj = iCourseInfoService.selectPage(new Page<>(offset, limit), ew);
            map.put("courseTotal", courseObj.getTotal());map.put("courseList", courseObj.getRecords());
        }
        if (type == 0 || type == 4) {
            EntityWrapper<PostsInfo> ew = new EntityWrapper<>();
            ew.like("LOWER(info.title)", searchName.toLowerCase());
            ew.orderBy(postsSort, isAsc == 1 ? false : true).orderBy("info.see_num", false);

            Page<PostsInfo> postsInfoObj = iPostsInfoService.selectPage(new Page<>(offset, limit), ew);
            map.put("postsInfoTotal", postsInfoObj.getTotal());map.put("postsInfoList", postsInfoObj.getRecords());
        }
        if (userId != null && StringUtils.isNotBlank(searchName)) {
            IndexSearchWord indexSearchWord = iIndexSearchWordService.selectOne(
                    new EntityWrapper<IndexSearchWord>().eq("user_id", userId).eq("word", searchName));
            if (indexSearchWord == null) {
                indexSearchWord = new IndexSearchWord();
                indexSearchWord.setCrtTime(new Date());
                indexSearchWord.setWord(searchName);
                indexSearchWord.setType(type);
                indexSearchWord.setUserId(userId);
                indexSearchWord.setCount(1);
                iIndexSearchWordService.insert(indexSearchWord);
            } else {
                indexSearchWord.setCrtTime(new Date());
                indexSearchWord.setType(type);
                indexSearchWord.setCount(indexSearchWord.getCount() + 1);
                iIndexSearchWordService.updateById(indexSearchWord);
            }
        }
        return new ReturnObject<>(0, "获取成功", map);
    }
}

